<template>
  <div class="container">
    <div class="header">
      <div class="item">
        <div class="title">总资产（人民币）</div>
        <div class="value">{{tool.formatNumber(total.totalAssets, '#0,000.00')}}</div>
      </div>
      <div class="item">
        <div class="title">证券市值</div>
        <div class="value">{{tool.formatNumber(total.marketValue, '#0,000.00')}}</div>
      </div>
      <div class="item">
        <div class="title">可用金额</div>
        <div class="value">{{tool.formatNumber(total.availableMoney, '#0,000.00')}}</div>
      </div>
      <div class="item">
        <div class="title">当日盈亏</div>
        <div :class="['value', total.todayProfit >=0 ? 'red' : 'green']">
          {{(total.todayProfit > 0 ? '+' : '') + tool.formatNumber(total.todayProfit, '#0,000.00')}}
        </div>
      </div>
      <div class="item">
        <div class="title">持仓盈亏</div>
        <div :class="['value', total.positionProfit >=0 ? 'red' : 'green']">
          {{(total.positionProfit > 0 ? '+' : '') + tool.formatNumber(total.positionProfit, '#0,000.00')}}
        </div>
      </div>
    </div>
    <div class="main">
      <el-table
        class="table"
        :data="dataList"
        key="id"
        :row-key="data => data.id"
      >
        <el-table-column
          label="名称/市值"
          header-align="center"
          align="center"
        >
          <template v-slot="scope">
            <div class="column">
              <div class="row-1">{{scope.row.name}}</div>
              <div class="row-2">{{scope.row.marketValue ? tool.formatNumber(scope.row.marketValue, '#0,000.00') : '--'}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="现价/成本"
          header-align="center"
          align="center"
        >
          <template v-slot="scope">
            <div class="column">
              <div class="row-1">{{scope.row.currPrice ? tool.formatNumber(scope.row.currPrice, '#0.00') : '--'}}</div>
              <div class="row-2">{{tool.formatNumber(scope.row.price, '#0.00')}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="持仓/可用"
          header-align="center"
          align="center"
        >
          <template v-slot="scope">
            <div class="column">
              <div class="row-1">{{scope.row.volume}}</div>
              <div class="row-2">{{scope.row.availableVolume}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="持仓盈亏"
          header-align="center"
          align="center"
        >
          <template v-slot="scope">
            <div :class="['column', scope.row.profit >= 0 ? 'red' : 'green']">
              <div class="row-1">{{(scope.row.profit > 0 ? '+' : '') + (scope.row.profit ? tool.formatNumber(scope.row.profit, "#0,000.00") : '--')}}</div>
              <div class="row-2">{{(scope.row.profit > 0 ? '+' : '') + (scope.row.profitRate ? tool.formatNumber(scope.row.profitRate * 100, "#0.00") + '%' : '--')}}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue';
import api from "@/http/api";
import {connectWebsocket, sendMessage} from "@/utils/websocket";
import {emitter} from "@/utils/bus";
import tool from "@/utils/tool";
import date from "@/utils/date";

const total = ref({
  totalAssets: 0,
  marketValue: 0,
  availableMoney: 0,
  todayProfit: 0,
  positionProfit: 0
});
const dataList = ref([]);
const accountList = ref([]);
const dealList = ref([]);
const lastPrice = ref({});

const dataListInter = ref();
const lastPriceInter = ref();

const loadData = async() => {
  let mbaRes = await api.post('/memberBrokerAccount/queryPage', {pageSize: 100});
  accountList.value = mbaRes.data || [];

  let param = {startDate: date.simpleDateFormat(new Date(), 'yyyy-MM-dd'), pageSize: 100};
  let sdRes = await api.post('/stockDeal/queryPage', param);
  dealList.value = sdRes.data || [];

  let spRes = await api.post('/stockPosition/queryPage', {pageSize: 100});
  dataList.value = spRes.data || [];

  calcValue();
};

const refreshLastPrice = () => {
  let codeList = [];
  (dataList.value || []).forEach(item => codeList.push(item.code));
  if (codeList.length > 0) {
    sendMessage({type: 'tick_list', code: codeList.join(',')});
  }
};

const tickListCallback = (data) => {
  lastPrice.value = data || {};
  calcValue();
}

const calcValue = () => {
  total.value.totalAssets = 0;
  total.value.availableMoney = 0;
  total.value.marketValue = 0;
  total.value.todayProfit = 0;
  total.value.positionProfit = 0;

  accountList.value.forEach(item => total.value.availableMoney += item.availableMoney || 0);
  dealList.value.forEach(item => total.value.todayProfit += item.profitMoney || 0);

  total.value.totalAssets += total.value.availableMoney;
  dataList.value.forEach(data => {
    let stockCode = data.code + '.' + data.exchangeCode;
    let priceObject = lastPrice.value[stockCode];
    if (priceObject && priceObject.lastPrice) {
      data.currPrice = priceObject.lastPrice;
      data.marketValue = data.volume * data.currPrice;
      data.profit = (data.volume * data.currPrice) - (data.volume * data.price);
      data.profitRate = data.profit / (data.volume * data.price || 1)
    }

    total.value.totalAssets += data.marketValue || 0;
    total.value.marketValue += data.marketValue || 0;
    total.value.positionProfit += data.profit || 0;
  });
};

onMounted(async() => {
  await loadData();
  await refreshLastPrice();
  dataListInter.value = setInterval(loadData, 10000);
  lastPriceInter.value = setInterval(refreshLastPrice, 10000);

  connectWebsocket();
  emitter.on("tick_list", (data) => tickListCallback(data));
});

onUnmounted(() => {
  clearInterval(dataListInter.value);
  clearInterval(lastPriceInter.value);
});
</script>

<style scoped lang="scss">
.red {
  color: rgb(249, 83, 66);
}
.green {
  color: rgb(12, 169, 0);
}
.container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  background: white;
  padding: 10px;
}
.header {
  display: flex;
  flex-direction: row;
  width: 100%;
  .item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
    height: 80px;
    .title {
      font-size: 16px;
    }
    .value {
      margin-top: 10px;
      font-size: 18px;
      font-weight: 600;
    }
  }
}
.main {
  flex-grow: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  height: 1px;
}
.table {
  .column {
    padding-top: 8px;
    line-height: 25px!important;
    div {
      padding: 0!important;
      margin: 0!important;
      line-height: unset!important;
    }
    .row-1 {
      font-weight: 600;
      font-size: 18px;
    }
    .row-2 {
      font-size: 14px;
    }
  }
}
</style>